<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019-10-18
 * Time: 13:59
 */

namespace app\manage\admin;
use app\admin\controller\Admin;
use app\common\builder\ZBuilder; // 引入ZBuilder
use app\common\model\Notice as NoticModel;
use app\common\model\Group as GroupModel;
use app\common\model\Users as UsersM;
use think\Db;

class Group extends Admin
{
    //团队列表
    public function index($pid = 1)
    {
        $topData = Db::name('qt_group')->whereIn('pid',['0','1'])->where('status',1)->order('sort asc id desc')->select();
        $list = Db::name('qt_group')->select();
        if($pid == '1'){
            $data = $this->getGroupMenu($list, 2, '0');
        }else{
            $data = $this->getNestMenu($list, 0, $pid);
        }
        return view('group/index', ['menus'=>$data,'top_data'=>$topData,'pid'=>$pid]);
    }

    /**
     * 新增节点
     * @param string $module 所属模块
     * @param string $pid 所属节点id
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     * @throws \Exception
     */
    public function add( $pid = '')
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');
            // 验证
            $result = $this->validate($data, 'Group.add');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
            // 顶部节点url检查
            $area = Db::name('qt_area')->where('id',$data['area'])->find();
            $city = Db::name('qt_area')->where('id',$area['pid'])->find();
            $province = Db::name('qt_area')->where('id',$city['pid'])->find();
            $data['province'] = $province['name'];
            $data['city'] = $city['name'];
            $data['area'] = $area['name'];
            if (GroupModel::create($data)) {
                $this->success('新增成功', url('index'));
            } else {
                $this->error('新增失败');
            }
        }
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增团队/部门')
            ->addFormItems([
                ['select', 'pid', '所属团队/部门', '所属上级部门', GroupModel::getMenuTree(0, ''), $pid],
            ])
            ->addFormItem(
                'text',
                'name',
                '团队/部门名称'
            )
            ->addImage('logo','请选择logo')
            ->addLinkages('area', '选择所在城市', '', 'qt_area','3')
            ->addFormItems([
                ['select:3', 'scale', '人员规模', '请选择', ['1'=>'0-20人','2'=>'20-100人','3'=>'100-500人','4'=>'500-1000人','5'=>'1000-3000人','6'=>'3000-10000人','7'=>'10000人以上']],
            ])
            ->addText('sort', '排序', '<code>越小越靠前</code>', 50)
            ->addRadio('status', '状态', '',['1'=>'正常','5'=>'禁用'],'1')
            ->fetch();
    }


    /**
     * 新增节点
     * @param string $module 所属模块
     * @param string $pid 所属节点id
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     * @throws \Exception
     */
    public function add_son( $pid = '',$team_id = '')
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');
            // 验证
            $result = $this->validate($data, 'Group.add');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
            if (GroupModel::create($data)) {
                $this->success('新增成功', url('index',['pid'=>$team_id]));
            } else {
                $this->error('新增失败');
            }
        }
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('新增团队/部门')
            ->addHidden('team_id',$team_id)
            ->addFormItems([
                ['select', 'pid', '所属团队/部门', '所属上级部门', GroupModel::getMenuTree(0, ''), $pid],
            ])
            ->addFormItem(
                'text',
                'name',
                '团队/部门名称'
            )
            ->addText('sort', '排序', '<code>越小越靠前</code>', 50)
            ->addRadio('status', '状态', '',['1'=>'正常','5'=>'禁用'],'1')
            ->fetch();
    }


    /**
     * 删除节点
     * @param array $record 行为日志内容
     * @author 蔡伟明 <314013107@qq.com>
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delete($record = [])
    {
        $id = $this->request->param('id');
        $menu = GroupModel::where('id', $id)->find();
        if ($menu['pid'] == '0') $this->error('该公司禁止删除');
        // 获取该节点的所有后辈节点id
        $menu_childs = GroupModel::getChildsId($id);
        // 要删除的所有节点id
        $all_ids = array_merge([(int)$id], $menu_childs);
        // 删除节点
        if (GroupModel::destroy($all_ids)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }


    /**
     * 编辑节点
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     * @throws \Exception
     */
    public function edit_son( $id = 0,$team_id = '')
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');
            // 验证
            $result = $this->validate($data, 'Group.add');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
            // 顶部节点url检查
            $area = Db::name('qt_area')->where('id',$data['area'])->find();
            $city = Db::name('qt_area')->where('id',$area['pid'])->find();
            $province = Db::name('qt_area')->where('id',$city['pid'])->find();
            $data['province'] = $province;
            $data['city'] = $city;
            $data['area'] = $area;
            if (GroupModel::update($data)) {
                $this->success('新增成功', url('index',['pid'=>$team_id]));
            } else {
                $this->error('新增失败');
            }
        }
        // 获取数据
        $info = GroupModel::get($id);
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑团队/部门')
            ->addFormItem('hidden', 'id')
            ->addFormItems([
                ['select', 'pid', '所属团队/部门', '所属上级部门', GroupModel::getMenuTree(0, '')],
            ])
            ->addFormItem(
                'text',
                'name',
                '团队/部门名称'
            )
            ->addText('sort', '排序', '<code>越小越靠前</code>', 50)
            ->addRadio('status', '状态', '',['1'=>'正常','5'=>'禁用'],'1')
            ->setFormData($info)
            ->fetch();
    }





    /**
     * 编辑节点
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     * @throws \Exception
     */
    public function edit( $id = 0,$team_id = '')
    {
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');
            // 验证
            $result = $this->validate($data, 'Group.add');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
            // 顶部节点url检查
            $area = Db::name('qt_area')->where('id',$data['area'])->find();
            $city = Db::name('qt_area')->where('id',$area['pid'])->find();
            $province = Db::name('qt_area')->where('id',$city['pid'])->find();
            $data['province'] = $province;
            $data['city'] = $city;
            $data['area'] = $area;
            if (GroupModel::update($data)) {
                $this->success('新增成功', url('index',['pid'=>$team_id]));
            } else {
                $this->error('新增失败');
            }
        }
        // 获取数据
        $info = GroupModel::get($id);
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑团队/部门')
            ->addFormItem('hidden', 'id')
            ->addFormItems([
                ['select', 'pid', '所属团队/部门', '所属上级部门', GroupModel::getMenuTree(0, '')],
            ])
            ->addFormItem(
                'text',
                'name',
                '团队/部门名称'
            )
            ->addImage('logo','请选择logo')
            ->addLinkages('area', '选择所在城市', '', 'qt_area','3')
            ->addFormItems([
                ['select:3', 'scale', '人员规模', '请选择', ['1'=>'0-20人','2'=>'20-100人','3'=>'100-500人','4'=>'500-1000人','5'=>'1000-3000人','6'=>'3000-10000人','7'=>'10000人以上']],
            ])
            ->addText('sort', '排序', '<code>越小越靠前</code>', 50)
            ->addRadio('status', '状态', '',['1'=>'正常','5'=>'禁用'],'1')
            ->setFormData($info)
            ->fetch();
    }

    /**
     * 设置岗位
     */
    public function set_up_post($group_id = '',$team_id = ''){
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');
            // 验证
            $result = $this->validate($data, 'Group.post_add');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
            // 顶部节点url检查
            $insertData = [];
            foreach ($data['post_id'] as $key=>$value){
                $insertData[$key]['group_id'] = $data['group_id'];
                $insertData[$key]['post_id'] = $value;
            }
            //删除记录并重新记录
            Db::name('qt_group_post')->where('group_id',$group_id)->delete();
            $insert = Db::name('qt_group_post')->insertAll($insertData);
            if ($insert) {
                $this->success('新增成功', url('index'));
            } else {
                $this->error('新增失败');
            }
        }
        $checkPost = Db::name('qt_group_post')->where('group_id',$group_id)->column('post_id');
        //岗位选项
        $groupName = Db::name('qt_group')->where('id',$group_id)->value('name');
        $postRes = Db::name('qt_post')->where('team_id',$team_id)->column('title','id');
        return ZBuilder::make('form')
            ->addFormItems(
                [
                    ['hidden:7','group_id',$group_id],
                    ['text:7','group_name','所属部门','',$groupName],
                    ['transfer:7','post_id','可选岗位','已选岗位','请选择要操作的岗位',$postRes,$checkPost],
                ]
            )
            ->setPageTitle('添加部门岗位')
            ->fetch();

    }



    /**
     * 设置人员
     */
    public function set_up_user($id = ''){
        $map = $this->getMap();
        $groupRes = $this->getGroup($id);
        foreach ($groupRes as $key=>$value){
            $groupIds[$key] = $value['id'];
            $groupIds['0'] = $id;
        }
        if(!isset($groupIds) && empty($groupIds)){
            $groupIds['0'] = $id;
        }
        $data_list=Db::name('qt_users')
            ->field('u.*,p.title')
            ->alias('u')
            ->leftJoin('qt_post p','u.post_id = p.id')
            ->order('id desc')
            ->where($map)
            ->whereIn('group_id',$groupIds)
            ->order('id desc')
            ->paginate();
        $page=$data_list->render();
        $title = Db::name('qt_group')->where('id',$id)->value('name');
        //$rank=RankM::column('rank_name','id');
        //设置按钮
        $btn_edit = [
            'title' => '岗位调整',
            'icon'  => 'fa fa-fw fa-cog',
            'class' => 'btn btn-xs btn-default',
            'href'  => url('user_post', ['id' => '__id__','group_id'=>$id]),
        ];
        //设置页面
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->addColumn('nickname','会员昵称','text')
            ->addColumn('phone', '手机', 'text')
            ->addColumn('work_number', '工号', 'text')
            ->addColumn('work_time', '入职日期', 'datetime','','Y/m/d H:i:s')
            ->addColumn('avatar', '头像', 'picture')
            ->addColumn('title', '岗位', 'text')
            ->addColumn('status','状态','status','',['1'=>'冻结:danger','0'=>'正常:success','3'=>'审核中:info'])
            ->addColumn('rank','审核权限','status','',['1'=>'普通','2'=>'审核','3'=>'超级审核'])
            ->addColumn('create_time', '注册日期', 'datetime','','Y/m/d H:i:s')
            ->addColumn('right_button','操作','btn')
            ->setTableName('qt_users') // 指定数据表名
            ->setSearchArea([
                ['text:2','nickname','姓名','like'],
                ['text:2','phone','手机','eq'],
                ['select:2','rank','权限状态','','',['1'=>'普通','2'=>'审核','3'=>'超级审核']],
                ['select:2','status','登录状态','','',['1'=>'冻结','0'=>'正常','3'=>'审核中']],
            ])
            ->addRightButton('edit',$btn_edit) // 添加右侧按钮
            //->addRightButton('money',$btn_money,['area'=>['70%','90%']]) // 添加右侧按钮
            ->setPrimaryKey('id') // 设置主键名
            ->setPageTitle($title.'下属人员岗位调整')
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch();
    }

    /**
     * 设置用户岗位
     * @param $id
     */
    public function user_post($group_id,$id){
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            if (UsersM::update($data)) {
                $this->success('设置岗位成功',url('manage/group/set_up_user',['id'=>$group_id]));
            }else{
                $this->error('设置岗位失败');
            }
        }else{
            $groupIds = [];
            //查找所有的部门
            $groupRes = $this->getGroup($group_id);
            foreach ($groupRes as $key=>$value){
                $groupIds[$key] = $value['id'];
                $groupIds['0'] = (int)$group_id;
            }
            if(empty($groupIds)){
                $groupIds['0'] = (int)$group_id;
            }
            //查找部门下面的岗位
            $postRes = Db::name('qt_group_post')
                ->alias('gp')
                ->leftJoin('qt_post p','gp.post_id = p.id')
                ->whereIn('gp.group_id',$groupIds)
                ->column('p.id,p.title');
            $userInfo  = Db::name('qt_users')->where('id',$id)->find();
            $teamRes = Db::name('qt_group')->whereIn('pid','0,1')->where('status','1')->column('name','id');
            $groupRes = Db::name('qt_group')->whereNotIn('pid','0,1')->where('status','1')->column('name','id');
            return ZBuilder::make('form')
                ->addFormItems(
                    [
                        ['hidden','id',$id],
                        ['text','nickname','昵称'],
                        ['text','work_number','工号'],
                        ['datetime','work_time','入职日期'],
                        ['text','phone','手机号码'],
                        ['select', 'team_id', '所属团队', '', $teamRes],
                        ['select', 'group_id', '所属部门', '', $groupRes],
                        ['radio', 'post_id', '所属岗位', '', $postRes],
                        ['radio', 'rank', '审核权限', '', ['1'=>'普通','2'=>'审核','3'=>'超级审核']],
                    ]
                )
                ->setFormData($userInfo)
                ->setPageTitle('会员信息')
                ->fetch();
        }
    }


    private function getGroup($groupId){
        static $res = array();
        $groupRes = Db::name('qt_group')->where('pid',$groupId)->select();
        if(empty($groupRes)){
            return $res;
        }else{
            foreach ($groupRes as $key=>$value){
                $res[] = $value;
                $chileGroupRes = Db::name('qt_group')->where('pid',$value['id'])->select();
                if(!empty($chileGroupRes)){
                    $this->getGroup($value['id']);
                }
            }
            return $res;
        }
    }

    /**
     * 获取嵌套式节点
     * @param array $lists 原始节点数组
     * @param int $pid 父级id
     * @param int $max_level 最多返回多少层，0为不限制
     * @param int $curr_level 当前层数
     * @author 蔡伟明 <314013107@qq.com>
     * @return string
     */
    private function getNestMenu($lists = [], $max_level = 0, $pid = 0, $curr_level = 1)
    {
        $result = '';
        static $team = '0';
        if($curr_level == '1') {
            $team = $pid;
        }
        foreach ($lists as $key => $value) {
            if ($value['pid'] == $pid) {
                $disable  = $value['status'] == 0 ? 'dd-disable' : '';
                // 组合节点
                $result .= '<li class="dd-item dd3-item '.$disable.'" data-id="'.$value['id'].'">';
                $result .= '<div class="dd-handle dd3-handle">拖拽</div><div class="dd3-content">'.$value['name'];
                $result .= '<div class="action">';
                $result .= '<a href="'.url('add_son', ['pid' => $value['id'],'team_id'=>$team]).'" data-toggle="tooltip" data-original-title="新增子节点"><i class="list-icon fa fa-plus fa-fw"></i></a><a href="'.url('edit_son', ['id' => $value['id'],'team_id'=>$team]).'" data-toggle="tooltip" data-original-title="编辑"><i class="list-icon fa fa-pencil fa-fw"></i></a>';
                $result .= '<a href="'.url('set_up_post', ['group_id' => $value['id'],'team_id'=>$team]).'" data-toggle="tooltip" data-original-title="设置岗位"><i class="list-icon fa fa-fw fa-cog"></i></a><a href="'.url('set_up_user', ['id' => $value['id']]).'" data-toggle="tooltip" data-original-title="人员设置"><i class="list-icon fa fa-fw fa-users"></i></a>';
                $result .= '<a href="'.url('delete', ['id' => $value['id']]).'" data-toggle="tooltip" data-original-title="删除" class="ajax-get confirm"><i class="list-icon fa fa-times fa-fw"></i></a></div>';
                $result .= '</div>';

                if ($max_level == 0 || $curr_level != $max_level) {
                    unset($lists[$key]);
                    // 下级节点
                    $children = $this->getNestMenu($lists, $max_level, $value['id'], $curr_level + 1);
                    if ($children != '') {
                        $result .= '<ol class="dd-list">'.$children.'</ol>';
                    }
                }

                $result .= '</li>';
            }
        }
        return $result;
    }


    /**
     * 获取嵌套式节点
     * @param array $lists 原始节点数组
     * @param int $pid 父级id
     * @param int $max_level 最多返回多少层，0为不限制
     * @param int $curr_level 当前层数
     * @author 蔡伟明 <314013107@qq.com>
     * @return string
     */
    private function getGroupMenu($lists = [], $max_level = 0, $pid = 0, $curr_level = 1)
    {
        $result = '';
        foreach ($lists as $key => $value) {
            if ($value['pid'] == $pid) {
                $disable  = $value['status'] == 0 ? 'dd-disable' : '';
                // 组合节点
                $result .= '<li class="dd-item dd3-item '.$disable.'" data-id="'.$value['id'].'">';
                $result .= '<div class="dd-handle dd3-handle">拖拽</div><div class="dd3-content">'.$value['name'];
                $result .= '<div class="action">';
                if($curr_level <= 2) {
                    $result .= '<a href="' . url('add', ['pid' => $value['id']]) . '" data-toggle="tooltip" data-original-title="新增团队"><i class="list-icon fa fa-plus fa-fw"></i></a><a href="' . url('edit', ['id' => $value['id']]) . '" data-toggle="tooltip" data-original-title="编辑"><i class="list-icon fa fa-pencil fa-fw"></i></a>';
                    $result .= '<a href="' . url('delete', ['id' => $value['id']]) . '" data-toggle="tooltip" data-original-title="删除" class="ajax-get confirm"><i class="list-icon fa fa-times fa-fw"></i></a></div>';
                }else{
                    $result .= '<a href="' . url('edit', ['id' => $value['id']]) . '" data-toggle="tooltip" data-original-title="编辑"><i class="list-icon fa fa-pencil fa-fw"></i></a>';
                    $result .= '<a href="' . url('delete', ['id' => $value['id']]) . '" data-toggle="tooltip" data-original-title="删除" class="ajax-get confirm"><i class="list-icon fa fa-times fa-fw"></i></a></div>';
                }
                $result .= '</div>';
                if ($max_level == 0 || $curr_level != $max_level) {
                    unset($lists[$key]);
                    // 下级节点
                    $children = $this->getGroupMenu($lists, $max_level, $value['id'], $curr_level + 1);
                    if ($children != '') {
                        $result .= '<ol class="dd-list">'.$children.'</ol>';
                    }
                }

                $result .= '</li>';
            }
        }
        return $result;
    }

    /**
     * 团队申请
     */
    public function register(){
        // 读取数据
        $map = $this->getMap();
        //dump($map);die;
        if(empty($map)){
            $map[0][0] = 'status';
            $map[0][1] = 'eq';
            $map[0][2] = '2';
        }
        // 排序
        $order = $this->getOrder();
        // 数据列表
        $data_list = GroupModel::where($map)->whereIn('pid',['1'])->order($order)->paginate();
        // 分页数据
        $page = $data_list->render();
        $btn_access1 = [
            'title' => '审核团队',
            'icon'  => 'fa fa-fw fa-pencil',
            'class' => 'btn btn-xs btn-default',
            'href'  => url('process', ['id' => '__id__']),
        ];
        //设置页面
        return ZBuilder::make('table')
            ->hideCheckbox()
            ->addColumn('id', '编号', 'text')
            ->addColumn('name', '团队名称', 'text')
            ->addColumn('logo', 'logo', 'picture')
            ->addColumn('scale', '人员规模', 'text')
            ->addColumn('created_time', '发布日期', 'datetime','','Y-m-d H:i:s')
            ->addColumn ('status', '状态', 'status','',[1=>'已审核:success', 2=>'待审核:info',3=>'审核失败:danger'])
            ->addColumn('right_button','操作','btn')
            ->setColumnWidth([
                'id'  => 100,
                'title' => 200,
                'status' => 200,
                'is_top'=>200,
                'create_time'=> 200,
                'update_time'=> 200,
                'right_button'=>200
            ])
            ->setTableName('qt_notic') // 指定数据表名
            ->addRightButton('edit',$btn_access1) // 添加右侧按钮
            ->addOrder('id,title,create_time,update_time')
            ->setPrimaryKey('id') // 设置主键名为username
            ->setSearchArea([
                ['text:2', 'name', '团队名称', 'like'],
                ['select:2', 'status', '状态', '', '', ['1' => '已审核', '2' => '待审核','3'=>'审核失败']],

            ])
            ->setPageTitle('团队申请列表')
            ->setRowList($data_list) // 设置表格数据
            ->setPages($page) // 设置分页数据
            ->fetch();
    }


    /**
     * 审核团队
     * @param string $id
     * @return mixed
     */
    public function process($id = ''){
        // 保存数据
        if ($this->request->isPost()) {
            $data = $this->request->post('', null, 'trim');
            // 验证
            $result = $this->validate($data, 'Group.add');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
            if(empty($data['status'])){
                $this->error('请选择是否通过');
            }
            // 顶部节点url检查
            $area = Db::name('qt_area')->where('id',$data['area'])->find();
            $city = Db::name('qt_area')->where('id',$area['pid'])->find();
            $province = Db::name('qt_area')->where('id',$city['pid'])->find();
            $data['province'] = $province;
            $data['city'] = $city;
            $data['area'] = $area;
            if (GroupModel::update($data)) {
                $this->success('新增成功', url('index'));
            } else {
                $this->error('新增失败');
            }
        }
        // 获取数据
        $info = GroupModel::get($id);
        // 使用ZBuilder快速创建表单
        return ZBuilder::make('form')
            ->setPageTitle('编辑团队/部门')
            ->addFormItem('hidden', 'id')
            ->addFormItems([
                ['select', 'pid', '所属团队/部门', '所属上级部门', GroupModel::getMenuTree(0, '')],
            ])
            ->addFormItem(
                'text',
                'name',
                '团队/部门名称'
            )
            ->addImage('logo','请选择logo')
            ->addLinkages('area', '选择所在城市', '', 'qt_area','3')
            ->addFormItems([
                ['select:3', 'scale', '人员规模', '请选择', ['1'=>'0-20人','2'=>'20-100人','3'=>'100-500人','4'=>'500-1000人','5'=>'1000-3000人','6'=>'3000-10000人','7'=>'10000人以上']],
            ])
            ->addRadio('status', '审核状态', '',['1'=>'通过','3'=>'不通过'])
            ->addTextarea('content', '审核意见')
            ->setFormData($info)
            ->fetch();
    }

}